package com.wswy.wzcx.utils;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.common.utils.BinaryUtil;
import com.alibaba.sdk.android.oss.model.ObjectMetadata;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.EncryptUtils;
import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.StatusUtil;
import com.liulishuo.okdownload.core.cause.ResumeFailedCause;
import com.liulishuo.okdownload.core.listener.DownloadListener3;
import com.wswy.wzcx.AppContext;
import com.wswy.wzcx.model.DataCenter;
import com.wswy.wzcx.model.UserMode;
import com.wswy.wzcx.model.core.OSSToken;
import com.wswy.wzcx.model.core.OSSUploadResult;
import com.wswy.wzcx.statistics.BizReport;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import timber.log.Timber;


public class FileUtils {

    private static final String TAG = "FileUtils";

    public static File getSaveFile(Context context) {
        return getSaveFile(context, "pic.jpg");
    }

    public static File getSaveFile(Context context, String name) {
        if (TextUtils.isEmpty(name)) {
            name = "pic.jpg";
        }
        File file = new File(context.getFilesDir(), name);

        if (!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }

        return file;
    }

    public static @Nullable
    File[] listFiles(Context context,String dir){
        File file = new File(context.getFilesDir(), dir);
        if (file.exists() && file.isDirectory()){
            return file.listFiles();
        }
        return null;
    }

    public static void deleteDir(Context context,String dir){
        File file = new File(context.getFilesDir(), dir);
        com.blankj.utilcode.util.FileUtils.deleteDir(file);
    }


    public static Map<String, OSSUploadResult> uploadToOSS(OSSToken token,Map<String,File> files)
        throws Exception {

        if (token == null || token.isInvalid()){
            throw new Exception("osstoken 无效 "+token);
        }

        if (files == null || files.isEmpty()){
            return Collections.emptyMap();
        }

        OSSStsTokenCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(token.getAccessKeyId(),
            token.getSecretKeyId(), token.getSecurityToken());

        OSSClient oss = new OSSClient(AppContext.getContext(), token.getEndpoint(), credentialProvider);

        Map<String,OSSUploadResult> map = new HashMap<>(files.size());

        Set<Entry<String, File>> entries = files.entrySet();

        for (Entry<String, File> entry : entries) {
            try {

                File file = entry.getValue();

                String objectKey = token.getUploadDir()+"/"+generateKey()+"."+com.blankj.utilcode.util.FileUtils.getFileExtension(file);
                Timber.e("objectKey "+objectKey);
                PutObjectRequest put =new  PutObjectRequest(token.getBucketName(), objectKey, file.getAbsolutePath());
                ObjectMetadata metadata =new ObjectMetadata();
                metadata.setContentMD5(BinaryUtil.calculateBase64Md5(file.getAbsolutePath()));
                put.setMetadata(metadata);
                PutObjectResult putObjectResult = oss.putObject(put);

                map.put(entry.getKey(),new OSSUploadResult(putObjectResult.getStatusCode(),objectKey,putObjectResult.getETag(),entry.getKey(),file));
            }catch (ServiceException e){
                BizReport.sendException(BizReport.OSS_UPLOAD_ERROR,e.getStatusCode()+":"+e.getErrorCode());
                Timber.e("upload error service:"+e.getStatusCode()+"   "+e.getErrorCode());
            }catch (Throwable e) {
                BizReport.sendException(BizReport.OSS_UPLOAD_ERROR,e.getMessage());
                Timber.e("upload error:"+e.getMessage());
                e.printStackTrace();
            }
        }


        return map;
    }

    private static String generateKey(){
        UserMode userMode = DataCenter.get().getUserMode();

        StringBuilder sb = new StringBuilder();
        if (userMode != null){
            sb.append(userMode.userAlias);
        }
        sb.append(System.currentTimeMillis());
        sb.append(UUID.randomUUID());
        return EncryptUtils.encryptMD5ToString(sb.toString());
    }




    public static void downloadApk(String url,String fileName){

        DownloadTask task = new DownloadTask.Builder(url, AppContext.getContext().getExternalFilesDir("download").getPath(),fileName)
            .setPassIfAlreadyCompleted(true)
            .build();

        Timber.e("----"+ StatusUtil.getStatus(task));


        DownloadTask.enqueue(new DownloadTask[]{task}, new DownloadListener3() {
            @Override
            protected void started(@NonNull DownloadTask task) {
                Timber.e( "started --> "+task.getFile());
            }

            @Override
            protected void completed(@NonNull DownloadTask task) {
                Timber.e( "completed --> "+task.getFile());
                try {
                    AppUtils.installApp(task.getFile());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void canceled(@NonNull DownloadTask task) {
                Timber.e("canceled --> "+task.getFile());
            }

            @Override
            protected void error(@NonNull DownloadTask task, @NonNull Exception e) {

            }

            @Override
            protected void warn(@NonNull DownloadTask task) {

            }

            @Override
            public void retry(@NonNull DownloadTask task, @NonNull ResumeFailedCause cause) {

            }

            @Override
            public void connected(@NonNull DownloadTask task, int blockCount, long currentOffset,
                long totalLength) {

            }

            @Override
            public void progress(@NonNull DownloadTask task, long currentOffset, long totalLength) {

            }
        });
    }

}
